//
//  AYTool.m
//  SuiXin
//
//  Created by mac on 2023/10/9.
//

#import "AYTool.h"
#import "AY_KeyChainStore.h"
#import <AdSupport/AdSupport.h>
#import <CoreText/CoreText.h>
#import <sys/utsname.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
//要导入头文件
#import <sys/utsname.h>

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static AFHTTPSessionManager *_mgr;
@implementation AYTool

+ (AFHTTPSessionManager *)getManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _mgr = [AFHTTPSessionManager manager];
        _mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html", @"application/x-www-form-urlencoded",@"text/plain", @"image/jpeg",nil];
        _mgr.requestSerializer = [AFJSONRequestSerializer serializer];
        _mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        [_mgr.requestSerializer setTimeoutInterval:10];
    });
    return _mgr;
}

#pragma mark - 获取当前viewController
+ (UIViewController *)viewControllerWith:(UIView *)childrenView {
    for (UIView *view = childrenView; view; view = view.superview) {
        UIResponder *nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

#pragma mark - 字体大小 以iPhone 5S为基准
+ (UIFont *)getFontWithSize:(CGFloat)size{
    CGFloat bili=size/375;
    //UIFont *font=[UIFont fontWithName:@"MicrosoftYaHei" size:bili*SCREEN_WIDTH];
    UIFont *font=[UIFont systemFontOfSize:bili*SCREEN_W];
    return font;
}

#pragma mark - 大小 以iPhone 5S为基准
+ (CGFloat)getNumberWith:(CGFloat)num{
    CGFloat bili=num/375;
    CGFloat current= bili*SCREEN_W;
    return current;
}

#pragma mark - 获取window
+ (UIWindow *)lastWindow
{
    NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows) {
        BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
        BOOL windowIsVisible = !window.hidden && window.alpha > 0;
        BOOL windowLevelSupported = (window.windowLevel >= UIWindowLevelNormal && window.windowLevel <= UIWindowLevelNormal);
        BOOL windowKeyWindow = window.isKeyWindow;
        
        if(windowOnMainScreen && windowIsVisible && windowLevelSupported && windowKeyWindow) {
            return window;
        }
    }
    
    return nil;
}

#pragma mark - 判断是否是夜间
+ (BOOL)isNight {
    if ([[AYMMKV getStringForKey:ReadTitleColor defaultValue:@"FEF6E9"] isEqual:@"999999"]) {
        return YES;
    }else {
        return NO;
    }
}

#pragma mark - 颜色转换 IOS中十六进制的颜色转换为UIColor
+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

+ (UIButton *)createButtonWithFrame:(CGRect)frame andTitle:(NSString *__nullable)title andFont:(UIFont *__nullable)font andTitleColor:(UIColor *__nullable)titleColor andBg:(UIColor *__nullable)color andImage:(UIImage *__nullable)imgae andBgImage:(UIImage *__nullable)bgImage andTarget:(id __nullable)target andAction:(SEL __nullable)action andRadius:(CGFloat)radius andAddSubView:(UIView *__nullable)subView
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    [btn setTitle:title forState:UIControlStateNormal];
    btn.backgroundColor = color;
    btn.titleLabel.font = font;
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn setImage:imgae forState:UIControlStateNormal];
    [btn setBackgroundImage:bgImage forState:UIControlStateNormal];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = radius;
    if (subView != nil) {
        [subView addSubview:btn];
    }
    return btn;
}

+ (UIView *)createViewWithFrame:(CGRect)frame andBg:(UIColor *__nullable)color andRadius:(CGFloat)radius andAddSubView:(UIView *__nullable)subView
{
    UIView *view = [[UIView alloc]init];
    view.frame = frame;
    view.backgroundColor = color;
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
    if (subView != nil) {
        [subView addSubview:view];
    }
    return view;
}

+ (UIImageView *)createImageViewWithFrame:(CGRect)frame andImage:(UIImage *__nullable)image andBg:(UIColor *__nullable)color andRadius:(CGFloat)radius andAddSubView:(UIView *__nullable)subView
{
    UIImageView *imageView = [[UIImageView alloc]init];
    
    imageView.frame = frame;
    
    [imageView setContentScaleFactor:[[UIScreen mainScreen] scale]];
    imageView.contentMode =  UIViewContentModeScaleAspectFill;
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    imageView.clipsToBounds  = YES;
    
    imageView.backgroundColor = color;
    imageView.image = image;
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = radius;
    if (subView != nil) {
        [subView addSubview:imageView];
    }
    return imageView;
}

+ (UILabel *)createLabelWithFrame:(CGRect)frame andText:(NSString *__nullable)text andTextColor:(UIColor *__nullable)textColor andBgColor:(UIColor *)bgColor andFont:(UIFont *__nullable)font andLines:(int)lineCount andRadius:(CGFloat)radius andAddSubView:(UIView *__nullable)subView
{
    UILabel *label = [[UILabel alloc]init];
    label.frame = frame;
    label.text = text;
    [label sizeToFit];
    label.textColor = textColor;
    if (bgColor) {
        label.backgroundColor = bgColor;
    }
    label.font = font;
    label.numberOfLines = lineCount;
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = radius;
    if (subView != nil) {
        [subView addSubview:label];
    }
    return label;
}


+ (UITableView *)creatMyTableView:(CGRect)frame {
    UITableView * myTableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    if (@available(iOS 11.0, *)) {
        myTableView.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        myTableView.sectionHeaderTopPadding = 0;
    }
    myTableView.showsVerticalScrollIndicator = NO;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GK_SCREEN_WIDTH, YNUM(10))];
    myTableView.backgroundColor = COLOR_Bg;
    return myTableView;
}

+ (UIImage*)buttonImageFromColor:(UIColor*)color{
    
    CGRect rect = CGRectMake(0,0,100,30);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context= UIGraphicsGetCurrentContext();  CGContextSetFillColorWithColor(context,[color CGColor]);
    
    CGContextFillRect(context,rect);
    
    UIImage*img= UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;

}

/**
 *  改变图片颜色
 */
+ (UIImage *)imageWithColor:(UIColor *)color and:(UIImage *)image
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextClipToMask(context, rect, image.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - 书籍状态
+ (void)setBookStatusWithStatus:(NSString *)status andLabel:(UILabel *)label {
    if ([status isEqual:@"1"]) {
        label.text = @"连载";
        label.backgroundColor = COLOR(@"fc6121");
    }else if ([status isEqual:@"2"]) {
        label.text = @"完结";
        label.backgroundColor = COLOR(@"46c939");
    }else {
        label.text = @"停更";
        label.backgroundColor = COLOR(@"8a8d96");
    }
}

/**
 设置渐变色
 @param color0 色值0
 @param color1 色值1
 @param size 尺寸
 @param type 方向 0水平方向 1竖直方向
 */
+ (UIColor *)customJianBianColorWithColor0:(UIColor *)color0 withColor1:(UIColor *)color1 withFrame:(CGSize)size withType:(NSInteger)type
{
    //    view.layer.masksToBounds = YES;
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    if (color0 != nil && color1 != nil) {
        gradientLayer.colors = @[(__bridge id)color0.CGColor, (__bridge id)color1.CGColor];
    }else{
        gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
    }
    gradientLayer.locations = @[@0,@1.0];
    gradientLayer.startPoint = CGPointMake(0,0);
    gradientLayer.endPoint = CGPointMake(1.0,0);
    if (type == 1) {
        gradientLayer.endPoint = CGPointMake(0,1.0);
    }
    gradientLayer.frame = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(size);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIColor *color = [UIColor colorWithPatternImage:image];
    return color;
}

+ (NSString *)homeFileName:(NSString *)fileName
{
    NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cacheStrPath = [NSString stringWithFormat:@"%@/%@",libPath,fileName];
    return cacheStrPath;
}

// 获取电子书字体样式
+(UIFont*)customFontWithPath:(NSString*)path size:(CGFloat)size
{
    NSURL *fontUrl = [NSURL fileURLWithPath:path];
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
    CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CTFontManagerRegisterGraphicsFont(fontRef, NULL);
    NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
    UIFont *font = [UIFont fontWithName:fontName size:size];
    CGFontRelease(fontRef);
    return font;
}

// 电子书格式化
+ (NSString *)bookFormateWithContent:(NSString *)content
{
    // 匹配所有连续空格和\n
//    content = [@"\n" stringByAppendingString:content];
    NSString *str = [content stringByReplacingOccurrencesOfString:@"\n" withString:@"&&"];
    str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@"&&"];
    str = [str stringByReplacingOccurrencesOfString:@"\t" withString:@"&&"];
    
    str = [AYTool bookMatchWithRegular:@"\\s+" adnWithReplacementStr:@"" andWithContent:str];
    // 匹配所有\n
    NSString *strRN = [AYTool bookMatchWithRegular:@"&&+" adnWithReplacementStr:@"\n" andWithContent:str];
//    return strRN;
    return content;
}

#pragma mark - 行间距
+ (NSMutableAttributedString *)LineSpacingTextWithText:(NSString *)text andSpace:(CGFloat)lineSpace
{
    // 描述行间距
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    [paragraphStyle setLineSpacing:lineSpace];//调整行间距
    
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    
    return attributedString;
}

#pragma mark - 获取文字
+ (NSString *)getContentWithUrl:(NSString *)url {
    __block NSString *str = @"";
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        dispatch_semaphore_signal(sem);
    });
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    return str;
}

/**
 *  获取当前时间
 */
+(NSString *)getCurrentTime
{
    NSDate *datenow = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[localeDate timeIntervalSince1970] - 28800];
    return timeSp;
}

// 正则匹配
+ (NSString *)bookMatchWithRegular:(NSString *)regular adnWithReplacementStr:(NSString *)str andWithContent:(NSString *)contentStr
{
    NSString * searchStr = contentStr;
    NSString * regExpStr = regular;
    NSString * replacement = str;
    // 创建 NSRegularExpression 对象,匹配 正则表达式
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:regExpStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
                                                                             NSString *resultStr = searchStr;
    // 替换匹配的字符串为 searchStr
    resultStr = [regExp stringByReplacingMatchesInString:searchStr
                                                     options:NSMatchingReportProgress
                                                       range:NSMakeRange(0, searchStr.length)
                                                withTemplate:replacement];
    return resultStr;
}


+ (NSString *)md5String:(NSString *)string{
    const char* input = [string UTF8String];
        unsigned char result[CC_MD5_DIGEST_LENGTH];
        CC_MD5(input, (CC_LONG)strlen(input), result);
        
        NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
        for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
            [digest appendFormat:@"%02X", result[i]];
        }
    return digest;
}

+ (NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];

    NSString *jsonString = @"";

    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符

    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    return jsonString;
}

//获取当前时间戳
+ (NSString *)getTimeNow {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这一点对时间的处理很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *dateNow = [NSDate date];
    NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)[dateNow timeIntervalSince1970]];
    return timeStamp;
}

+ (NSString *)getTimeNowDate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"]; // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    return dateStr;
}

#pragma mark - 获取UUID
+ (NSString *)getUUID {
    // 这个key的前缀最好是你的BundleID
    NSString*strUUID = (NSString*)[AY_KeyChainStore load:SXAPPBUNDLEID];
    //首次执行该方法时，uuid为空
    if([strUUID isEqualToString:@""]|| !strUUID)
    {
    // 获取UUID 这个是要引入<AdSupport/AdSupport.h>的
    strUUID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if(strUUID.length ==0 || [strUUID isEqualToString:UUID00x00])
    {
        //生成一个uuid的方法
        CFUUIDRef uuidRef= CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
        CFRelease(uuidRef);
    }
    //将该uuid保存到keychain
    [AY_KeyChainStore save:SXAPPBUNDLEID data:strUUID];
   }
    NSString *uuid = [strUUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return uuid;
}

+ (NSString*)encrypt:(NSString*)plainText {
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    size_t plainTextBufferSize = [data length];
    const void *vplainText = (const void *)[data bytes];
    
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    
    bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [DESkey UTF8String];
    const void *vinitVec = (const void *) [DESIv UTF8String];
    
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithmDES,
                       kCCOptionPKCS7Padding | kCCOptionECBMode,
                       vkey,
                       kCCKeySizeDES,
                       NULL,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
    NSString *result = [self base64EncodedStringFrom:myData];
//    NSString *result = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
    return result;
}

// 获取手机型号
+ (NSString *)getPhoneDeviceType{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    // iPhone
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    if ([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    if ([platform isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([platform isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if ([platform isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    if ([platform isEqualToString:@"iPhone11,4"]) return @"iPhone XS Max";
    if ([platform isEqualToString:@"iPhone12,1"]) return @"iPhone 11";
    if ([platform isEqualToString:@"iPhone12,3"]) return @"iPhone 11 Pro";
    if ([platform isEqualToString:@"iPhone12,5"]) return @"iPhone 11 Pro Max";
    if ([platform isEqualToString:@"iPhone12,8"]) return @"iPhone SE(2nd generation)";
    if ([platform isEqualToString:@"iPhone13,1"]) return @"iPhone 12 mini";
    if ([platform isEqualToString:@"iPhone13,2"]) return @"iPhone 12";
    if ([platform isEqualToString:@"iPhone13,3"]) return @"iPhone 12 Pro";
    if ([platform isEqualToString:@"iPhone13,4"]) return @"iPhone 12 Pro Max";
    if ([platform isEqualToString:@"iPhone14,4"]) return @"iPhone 13 mini";
    if ([platform isEqualToString:@"iPhone14,5"]) return @"iPhone 13";
    if ([platform isEqualToString:@"iPhone14,2"]) return @"iPhone 13 Pro";
    if ([platform isEqualToString:@"iPhone14,3"]) return @"iPhone 13 Pro Max";
    if ([platform isEqualToString:@"iPhone14,6"]) return @"iPhone SE (3rd generation)";
    if ([platform isEqualToString:@"iPhone14,7"]) return @"iPhone 14";
    if ([platform isEqualToString:@"iPhone14,8"]) return @"iPhone 14 Plus";
    if ([platform isEqualToString:@"iPhone15,2"]) return @"iPhone 14 Pro";
    if ([platform isEqualToString:@"iPhone15,3"]) return @"iPhone 14 Pro Max";
    if ([platform isEqualToString:@"iPhone15,4"]) return @"iPhone_15";
    if ([platform isEqualToString:@"iPhone15,5"]) return @"iPhone_15_Plus";
    if ([platform isEqualToString:@"iPhone16,1"]) return @"iPhone_15_Pro";
    if ([platform isEqualToString:@"iPhone16,2"]) return @"iPhone_15_Pro_Max";
    if ([platform isEqualToString:@"iPhone17,3"]) return @"iPhone_16";
    if ([platform isEqualToString:@"iPhone17,4"]) return @"iPhone_16_Plus";
    if ([platform isEqualToString:@"iPhone17,1"]) return @"iPhone_16_Pro";
    if ([platform isEqualToString:@"iPhone17,2"]) return @"iPhone_16_Pro_Max";
    // iPod Touch
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5";
    if ([platform isEqualToString:@"iPod7,1"])   return @"iPod Touch 6";
    if ([platform isEqualToString:@"iPod9,1"])   return @"iPod Touch 7";
    //iPad Mini
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2";
    if ([platform isEqualToString:@"iPad4,7"])   return @"iPad Mini 3";
    if ([platform isEqualToString:@"iPad4,8"])   return @"iPad Mini 3";
    if ([platform isEqualToString:@"iPad4,9"])   return @"iPad Mini 3";
    if ([platform isEqualToString:@"iPad5,1"])   return @"iPad Mini 4";
    if ([platform isEqualToString:@"iPad5,2"])   return @"iPad Mini 4";
    if ([platform isEqualToString:@"iPad11,1"])  return @"iPad Mini 5";
    if ([platform isEqualToString:@"iPad11,2"])  return @"iPad Mini 5";
    if ([platform isEqualToString:@"iPad14,1"])  return @"iPad Mini 6";
    if ([platform isEqualToString:@"iPad14,2"])  return @"iPad Mini 6";
    //iPad Pro
    if ([platform isEqualToString:@"iPad6,3"])   return @"iPad Pro_9.7";
    if ([platform isEqualToString:@"iPad6,4"])   return @"iPad Pro_9.7";
    if ([platform isEqualToString:@"iPad6,7"])   return @"iPad Pro_12.9";
    if ([platform isEqualToString:@"iPad6,8"])   return @"iPad Pro_12.9";
    if ([platform isEqualToString:@"iPad7,1"])   return @"iPad Pro 2_12.9";
    if ([platform isEqualToString:@"iPad7,2"])   return @"iPad Pro 2_12.9";
    if ([platform isEqualToString:@"iPad7,3"])   return @"iPad Pro_10.5";
    if ([platform isEqualToString:@"iPad7,4"])   return @"iPad Pro_10.5";
    if ([platform isEqualToString:@"iPad8,1"])   return @"iPad Pro_11";
    if ([platform isEqualToString:@"iPad8,2"])   return @"iPad Pro_11";
    if ([platform isEqualToString:@"iPad8,3"])   return @"iPad Pro_11";
    if ([platform isEqualToString:@"iPad8,4"])   return @"iPad Pro_11";
    if ([platform isEqualToString:@"iPad8,5"])   return @"iPad Pro 3_12.9";
    if ([platform isEqualToString:@"iPad8,6"])   return @"iPad Pro 3_12.9";
    if ([platform isEqualToString:@"iPad8,7"])   return @"iPad Pro 3_12.9";
    if ([platform isEqualToString:@"iPad8,8"])   return @"iPad Pro 3_12.9";
    if ([platform isEqualToString:@"iPad8,8"])   return @"iPad Pro 2_11";
    if ([platform isEqualToString:@"iPad8,10"])  return @"iPad Pro 2_11";
    if ([platform isEqualToString:@"iPad8,11"])  return @"iPad Pro 4_12.9";
    if ([platform isEqualToString:@"iPad8,12"])  return @"iPad Pro 4_12.9";
    if ([platform isEqualToString:@"iPad13,4"])  return @"iPad Pro 3_11";
    if ([platform isEqualToString:@"iPad13,5"])  return @"iPad Pro 3_11";
    if ([platform isEqualToString:@"iPad13,6"])  return @"iPad Pro 3_11";
    if ([platform isEqualToString:@"iPad13,7"])  return @"iPad Pro 3_11";
    if ([platform isEqualToString:@"iPad13,8"])  return @"iPad Pro 5_12.9";
    if ([platform isEqualToString:@"iPad13,9"])  return @"iPad Pro 5_12.9";
    if ([platform isEqualToString:@"iPad13,10"]) return @"iPad Pro 5_12.9";
    if ([platform isEqualToString:@"iPad13,11"]) return @"iPad Pro 5_12.9";
    if ([platform isEqualToString:@"iPad14,3"]) return @"iPad Pro 4_11";
    if ([platform isEqualToString:@"iPad14,4"]) return @"iPad Pro 4_11";
    if ([platform isEqualToString:@"iPad14,5"]) return @"iPad Pro 6_12.9";
    if ([platform isEqualToString:@"iPad14,6"]) return @"iPad Pro 6_12.9";
    if ([platform isEqualToString:@"iPad16,3"]) return @"iPad Pro M4_11";
    if ([platform isEqualToString:@"iPad16,4"]) return @"iPad Pro M4_11";
    if ([platform isEqualToString:@"iPad16,5"]) return @"iPad Pro M4_13";
    if ([platform isEqualToString:@"iPad16,6"]) return @"iPad Pro M4_13";
    //iPad Air
    if ([platform isEqualToString:@"iPad4,1"])    return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,2"])    return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,3"])    return @"iPad Air";
    if ([platform isEqualToString:@"iPad5,3"])    return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad5,4"])    return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad11,3"])   return @"iPad Air 3";
    if ([platform isEqualToString:@"iPad11,4"])   return @"iPad Air 3";
    if ([platform isEqualToString:@"iPad13,1"])   return @"iPad Air 4";
    if ([platform isEqualToString:@"iPad13,2"])   return @"iPad Air 4";
    if ([platform isEqualToString:@"iPad13,3"])   return @"iPad Air 4";
    if ([platform isEqualToString:@"iPad13,16"])   return @"iPad Air 5";
    if ([platform isEqualToString:@"iPad13,17"])   return @"iPad Air 5";
    if ([platform isEqualToString:@"iPad14,8"])   return @"iPad Air M2_11";
    if ([platform isEqualToString:@"iPad14,9"])   return @"iPad Air M2_11";
   if ([platform isEqualToString:@"iPad14,10"])   return @"iPad Air M2_13";
    if ([platform isEqualToString:@"iPad14,11"])   return @"iPad Air M2_13";
    //iPad
    if ([platform isEqualToString:@"iPad1,1"])    return @"iPad 1";
    if ([platform isEqualToString:@"iPad2,1"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,2"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,4"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad3,1"])    return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,2"])    return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,3"])    return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])    return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,5"])    return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])    return @"iPad 4";
    if ([platform isEqualToString:@"iPad6,11"])   return @"iPad 5";
    if ([platform isEqualToString:@"iPad6,12"])   return @"iPad 5";
    if ([platform isEqualToString:@"iPad7,5"])    return @"iPad 6";
    if ([platform isEqualToString:@"iPad7,6"])    return @"iPad 6";
    if ([platform isEqualToString:@"iPad7,11"])   return @"iPad 7";
    if ([platform isEqualToString:@"iPad7,12"])   return @"iPad 7";
    if ([platform isEqualToString:@"iPad11,6"])   return @"iPad 8";
    if ([platform isEqualToString:@"iPad11,7"])   return @"iPad 8";
    if ([platform isEqualToString:@"iPad12,1"])   return @"iPad 9";
    if ([platform isEqualToString:@"iPad12,2"])   return @"iPad 9";
    if ([platform isEqualToString:@"iPad13,18"])   return @"iPad 10";
    if ([platform isEqualToString:@"iPad13,19"])   return @"iPad 10";
    //模拟器
    if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    return platform;
}

+ (NSString *)base64EncodedStringFrom:(NSData *)data
{
    if ([data length] == 0)
        return @"";
    
    char *characters = malloc((([data length] + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (i < [data length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [data length])
            buffer[bufferLength++] = ((char *)[data bytes])[i++];
        
        //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    
    return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSUTF8StringEncoding freeWhenDone:YES];
}

#pragma mark - ascii 排序
+ (NSString *)sortedDictionary:(NSDictionary *)dict {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:dict];
    [dic addEntriesFromDictionary:[self headerDic]];
    
    //将所有的key放进数组
    NSArray *allKeyArray = [dic allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArra = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
        obj1 = [obj1 lowercaseString];
        obj2 = [obj2 lowercaseString];
        //排序操作
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    NSMutableArray *afterSortKeyArray = [NSMutableArray arrayWithArray:afterSortKeyArra];
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dic objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    NSString *str = @"";
    for (int i =0; i < afterSortKeyArray.count; i++) {
        if (kStringIsEmpty(valueArray[i])) {
            [valueArray removeObjectAtIndex:i];
            [afterSortKeyArray removeObjectAtIndex:i];
        }
        if (kStringIsEmpty(str)) {
            str = [NSString stringWithFormat:@"%@=%@",afterSortKeyArray[i],valueArray[i]];
        }else {
            str = [NSString stringWithFormat:@"%@&%@=%@",str,afterSortKeyArray[i],valueArray[i]];
        }
    }
    return [NSString stringWithFormat:@"%@&key=%@",str,SXKEY];
}

#pragma mark - 网络header
+ (NSDictionary *)headerDic {
    NSDictionary *signDic = @{
        @"deviceUuid": [AYTool getUUID],
        @"appVersion": APPVERSION,
        @"appPackageCode": SXAPPBUNDLEID,
        @"channelCode": CHANNELCODE,
        @"osType": @"iOS",
        @"deviceManufacturer": [NSString stringWithFormat:@"apple-v-%@-v-%@",[self getPhoneDeviceType], [UIDevice currentDevice].systemVersion]
    };
    return signDic;
}

#pragma mark - 排序算法
//数组升序
+ (NSArray *)sortASC:(NSArray *)ary {
    if (!kArrayIsEmpty(ary) && ary.count > 1) {
        //对数组进行排序
        NSArray *result = [ary sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2]; //升序
        }];
        NSLog(@"sortNo排序后的值====>>> %@",result);
        return result;
    }else {
        return ary;
    }
}

#pragma 保存图书
+ (void)saveBooksWithBookId:(NSString *)bookId andPage:(NSInteger)page andChapterIndex:(NSInteger)chapterIndex {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[]];
    NSData *historyData = [AYMMKV getDataForKey:READHISTORY defaultValue:data];
    NSMutableArray *historys = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:historyData]];
    if ([AYTool isExistBookWithBookId:bookId andDataSource:historys]) {
        for (int i =0; i < historys.count; i++) {
            AY_ReadBookModel *model = historys[i];
            if ([model.bookId isEqual:bookId]) {
                model.chapterIndex = [NSString stringWithFormat:@"%lu",chapterIndex];
                model.page = [NSString stringWithFormat:@"%lu",page];
                [historys removeObjectAtIndex:i];
                [historys insertObject:model atIndex:0];
            }
        }
    }else {
        AY_ReadBookModel *model = [[AY_ReadBookModel alloc] init];
        model.bookId = bookId;
        model.page = [NSString stringWithFormat:@"%lu",page];
        model.chapterIndex = [NSString stringWithFormat:@"%lu",chapterIndex];
        [historys insertObject:model atIndex:0];
    }
    NSData *bookData = [NSKeyedArchiver archivedDataWithRootObject:historys];
    [AYMMKV setData:bookData forKey:READHISTORY];
}

#pragma 取出图书数据
+ (AY_ReadBookModel *)getBookDataWithBookId:(NSString *)bookId {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[]];
    NSData *historyData = [AYMMKV getDataForKey:READHISTORY defaultValue:data];
    NSMutableArray *historys = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:historyData]];
    AY_ReadBookModel *emptyModel = [[AY_ReadBookModel alloc] init];
    emptyModel.bookId = bookId;
    emptyModel.page = 0;
    emptyModel.chapterIndex = 0;
    if ([AYTool isExistBookWithBookId:bookId andDataSource:historys]) {
        for (AY_ReadBookModel *model in historys) {
            if ([model.bookId isEqual:bookId]) {
                return model;
            }
        }
        return emptyModel;
    }else {
        return emptyModel;
    }
}

+ (BOOL)isExistBookWithBookId:(NSString *)bookId andDataSource:(NSMutableArray *)dataSource {
    BOOL contains = NO;
    for (AY_ReadBookModel *model in dataSource) {
        if ([model.bookId isEqual:bookId]) {
            contains = YES;
            break;
        }
    }
    return contains;
}

////单独处理返回json数据按sort排序
//+ (NSArray *)sortCommonBySoreNo:(AY_BaseModel *)baseModel {
//    NSMutableArray * sortNoAry = [@[] mutableCopy];
//
//    for (SortModel *sorModel in baseModel) {
//        if (!kStringIsEmpty(sorModel.sortNo)) {
//            [sortNoAry addObject:[NSNumber numberWithInt:[kStringUtils(sorModel.sortNo) intValue]]];
//        }
//    }
//    //先排序处理数据
//    sortNoAry = [NSMutableArray arrayWithArray:[AYTool sortASC:sortNoAry]];
//
//
//    if (!kStringIsEmpty(str)) {
//        [sortNoAry addObject:[NSNumber numberWithInt:[kStringUtils(str) intValue]]];
//    }
//    sortNoAry = [NSMutableArray arrayWithArray:[AYTool sortASC:sortNoAry]];
//    return sortNoAry;
//}

+ (void)cornerView:(UIView *)view andWithRoundingCorners:(UIRectCorner)corners ornerRadii:(CGSize)cornerRadii
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

@end
